/**
 * 重大任务; 总体计划
 *
 * 作者 nie
 * 日期 2024-10-23 14:58:05
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'layer', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        layer = layui.layer,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-task'),
        $query = $view.find('#query'),
        $export = $view.find('#export'),
        $taskStartDate=$view.find("#taskStartDate");
        $taskEndDate=$view.find("#taskEndDate");
        $oneKeyAssemblie = $view.find('#oneKeyAssemblie'),
        $commit = $view.find('#commit'),
        $audit = $view.find('#audit'),
        $transferStation = $view.find('#transferStation'),
        $status = $view.find('#status'),
        $searchForm = $view.find('#task-table-form');
       var  reasonData='';
        initNotice();

    laydate.render({
        elem: '#ID-laydate-range',
        type:'date',
        format: 'yyyy-MM-dd',
        btns: ['now', 'confirm'],
        trigger: 'click',
        isInitValue: true,
        range: ['#taskStartDate', '#taskEndDate'],
        done: function(value, date) {
            $query.click();
        }
    });

    form.verify(validate);
    form.render();
    febs.initDictItemSelect($status, 'TASK_STATUS', null, null);

    var ganttCustom, showType = 'day';
    var mySchedule = '0';
    var  transferData=[];
    var ganStartTime = formatDateDorward(getCurrentDay(),-7);
    var  ganEndTime=formatNextYear(getCurrentDay());
    var taskId;
    var  rsDirector;
    var  managerids;


    $taskStartDate.val(ganStartTime);
    $taskEndDate.val(ganEndTime);
    var   ganttData = getData(ctx + "schedule/list", getQueryParams())||[];
    reloadGantt();

    function getData(url, condition) {
        var result = [];
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data.list || [];
                reasonData=data.reason;
            },
        });
        return result;
    }

    function getTestData(url, condition) {
        var result = [];
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data || [];
            },
        });
        return result;
    }

    // 甘特图 获取数据
    function reloadGantt() {
        gantt_draw();

        classArr = document.getElementsByClassName("gantt_handle_two") || [];
        for (i = 0; i < classArr.length; i++) {
            classArr[i].addEventListener("click", function (event) {
                var rscode = this.getAttribute('code');
             var  hasAuth=  febs.include(permissionSet,"schedule:taskTestExcel");
             var button=['导出'];
             if(!hasAuth){
                 button=['关闭']
             }
                layer.open({
                    type: 1,
                    title: '试验计划',
                    offset: ['100px', '40px'],
                   area: $(window).width() <= 750 ? ['85%', '70%'] : ['85%', '300px'],
                    btn: button,
                    closeBtn: 1,
                    content: $('#taskTestForm'),
                    yes: function (layero, index) {
                        if(hasAuth){
                            var condition = {rsCode: rscode, invalidate_ie_cache: new Date()};
                            febs.download(ctx + 'schedule/taskTestExcel', condition, '试验计划.xlsx');
                        }else {
                            layer.closeAll();
                        }

                    }, cancle() {
                    }
                });
                var condition = {rsCode: rscode, invalidate_ie_cache: new Date()};
                var data = getTestData(ctx + 'schedule/taskTestList', condition);
                initTaskTestTable(data);
            });
        }

    }

    function initTaskTestTable(data) {
        febs.table.init({
            elem: '#taskTestTable',
            data: data,
            page: false,
            loading: true,
            // even: false,
            height: getTableHeight() / 4,
            cols: [[
                {title: '试验时间', field: 'planStartStr', minWidth: 150},
                {title: '项目编号', field: 'projectCode', minWidth: 120, edit: false},
                {field: 'shipCode', title: '船模编号', minWidth: 120, edit: false},
                {field: 'rsDirectorName', title: '负责人', minWidth: 100, edit: false},
                {field: 'testrecord', title: '试验状态', minWidth: 180, edit: false},
                {field: 'remark', title: '备注', minWidth: 180, edit: false},
                {field: 'shipName', title: '船名', minWidth: 150, edit: false},
                {field: 'custName', title: '客户', minWidth: 150, edit: false},
            ]],
            done: function (res, curr, count) {
            }
        });
    }

    // 绘制 甘特图

    function gantt_draw() {
        let settings = {
            tableData: ganttData,
            stepWidth: 15,
            showType: showType,
            startTime: ganStartTime,//右侧表格显示的最小日期
            endTime: ganEndTime,//右侧表格显示的最大日期
            leftShowColNum : 2,
            dlclick(ele) {
                // taskId,startdate, enddate
                // open_dialog(ele);
                taskId = ele.taskId;
                rsDirector=ele.rsDirector;
                managerids=ele.managerids;
                $('#pqdialog').css({"left": ele.left + "px", "top": ele.top-20 + "px" ,"display":  "flex"});
                if(ele.status==6||ele.status==7){
                    $('#pqdialog').find('#approve').css({"display": "none"});
                    $('#pqdialog').find('#auditOperator').css({"display": "none"});
                    $('#pqdialog').find('#edit').css({"display": "none"});
                    $('#pqdialog').find('#transfer').css({"display": "none"});
                    $('#pqdialog').find('#del').css({"display": "none"});
                }else if(ele.rsDirector==useridData &&ele.status==2 ){
                    $('#pqdialog').find('#approve').css({"display": "block"});
                    $('#pqdialog').find('#edit').css({"display": "block"});
                    $('#pqdialog').find('#transfer').css({"display": "block"});
                    $('#pqdialog').find('#del').css({"display": "block"});
                }else  if(ele.rsDirector==useridData||  isAdminData==true ||ele.managerids!=null&&ele.managerids.split(',').includes(useridData) ){
                    $('#pqdialog').find('#approve').css({"display": "none"});
                    $('#pqdialog').find('#edit').css({"display": "block"});
                    $('#pqdialog').find('#transfer').css({"display": "block"});
                    $('#pqdialog').find('#del').css({"display": "block"});
                }
                // if(ele.status==3){
                //     $("#reamrkid").css("display","inline-block");
                //     var str=taskId+'任务排期审核未通过11，原因'+ele.reason+',请及时修改!';
                //     $("#reamrkid").html(str);
                // }else {
                //     $("#reamrkid").css("display","none");
                //     $("#reamrkid").html('');
                // }

                $('#pqdialog').find('li').hover(function () {
                    $(this).css("background","antiquewhite");

                },function () {
                    $(this).css("background","none");
                })
            },
            //拉伸之后的回调事件
            resizeHandle(ele) {
                // taskId, startTime, endTime
                // console.log('拉伸之后的回调事件-------', ele)
                // ganttProgressMoveEnd(ele);
            },//拖拽之后的回调事件
            dragHandle(ele) {
                console.log('拖拽之后的回调事件-------', ele);
                let planStartdate=ele.startTime;
                let planEndate=ele.endTime;
                let planStarttime = ele.startMidFlg == 'true' ? '12:00:00' : '09:00:00';
                let planEndtime = ele.endMidFlg == 'true' ? '12:00:00' : '17:00:00';
                var status=ele.staus;
                var data={
                    taskCode:ele.taskId,
                    planStartdate:planStartdate,
                    planEnddate:planEndate,
                    planStarttime:planStarttime,
                    planEndtime:planEndtime,
                    status: status,
                };


                //检查资源是否被占用
            var info=     checkData(ctx + 'schedule/check', data);
                if(info.length>0){
                    reloadGantt();
                    layer.msg(info);
                    return;
                }

                // taskId, startTime, endTime
                febs.postArray(ctx + 'schedule/update', data, function (d) {
                });
                modiSchdeuleStep(ele.taskId,'','','',planStartdate,planEndate,ele.startMidFlg,ele.endMidFlg,status);
            }
        };
        if (!ganttCustom) { // 首次渲染
            settings.elem = '#mainGanttBox';
            ganttCustom = new GanttCustom(settings);
        } else {
            ganttCustom = ganttCustom.reload(settings);
        }
    }

    $query.on('click', function () {
        ganttData = getData(ctx + "schedule/list", getQueryParams()) || [];
        reloadGantt();
    });

    $export.on('click', function () {
        febs.download(ctx + 'schedule/excel', getQueryParams(), '排期信息.xlsx');
    });

    $oneKeyAssemblie.on('click', function () {
        febs.get(ctx + 'schedule/oneKeyAssemblie/', null, function () {
            $query.trigger('click');
            layer.msg('一键排期完成');
            //刷新页面
            reloadGantt();
        });

    });

    $commit.on('click', function () {
        if (transferData != null && transferData.length > 0) {
            layer.msg('任务中转站尚未未排期任务，请全部排完之后再执行该操作!');
            return;
        }
        febs.get(ctx + 'schedule/batchCommit/', null, function () {
            layer.msg('批量提交完成');
            $query.trigger('click');
        });
    });

    $audit.on('click', function () {
        if (transferData != null && transferData.length > 0) {
            layer.msg('任务中转站尚未未排期任务，请全部排完之后再执行该操作!');
            return;
        }
        febs.get(ctx + 'schedule/batchAudit/', '', function () {
            layer.msg('一键审批完成');
            $query.trigger('click');
        });
    });

    $transferStation.on('click', function () {
        layer.open({
            type: 1,
            title: '任务中转站',
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['90%', '60%'],
            btn: [],
            closeBtn:1,
            offset: ['100px','40px'],
            content :$('#transforForm'),
            success: function (layero, index) {
            },cancle(){
            }
        });
        initTransTable();

    });

      //在form外面 ,事件不生效
    // form.on('checkbox(mySchedule)', function (data) {
    //     if (data.elem.checked) {
    //         mySchedule = '1';
    //     } else {
    //         mySchedule = '0';
    //     }
    // });

     debugger;
     if($('#mySchedule').length>0){
         document.getElementById('mySchedule').addEventListener('change', function() {
             if(this.checked) {
                 // checkbox被选中时的操作
                 mySchedule = '1';
             } else {
                 // checkbox未被选中时的操作
                 mySchedule = '0';
             }
             $query.click();
         });
     }


    function  modifyTask(taskid,rsDirector){
        febs.modal.open('修改排期', 'schedule/updateSchedule/' + taskid, {
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '77%'],
            btn: [ '保存并提交'],
            offset: ['5px', '5px'],
            yes: function (index, layero) {
                $('#task-edit').find('#submit').trigger('click');
                var isSuccess = $(layero).find('#isSuccess').val();
                 if(isSuccess=='false'){
                     return  false;
                 }
                 var rsCode=$(layero).find('#rsCode').val();
                 var managerids=$(layero).find("#managerids").val();
                var startdate = $(layero).find('#planStartdate').val();
                var enddate = $(layero).find('#planEnddate').val();
                var starttime= $(layero).find('#planStarttime').val();
                var  endtime= $(layero).find('#planEndtime').val();
                var  startMidFlg=false;
                if("12:00"==starttime){
                    startMidFlg=true;
                }
                var endMidFlg=false;
                if("12:00"==endtime){
                    endMidFlg=true;
                }
                 if(rsDirector==useridData){
                    modiSchdeuleStep(taskid,rsCode,managerids,rsDirector,startdate,enddate,startMidFlg,endMidFlg,"4");
                }else {
                    modiSchdeuleStep(taskid,rsCode,managerids,rsDirector,startdate,enddate,startMidFlg,endMidFlg,"2");
                }
               //将任务从中间站移除

                layer.close(index);
            },
            btn2: function (index, layero) {
                }, success: function (index, layero) {
            }, data: {},
            success:function (index, layero){
            }

            });

    }


    function   modiSchdeuleStep(taskid,rsCode,managerids,rsDirector,startTime,endTime,startMidFlg,endMidFlg,status){
        var isfind='false';
        ganttData.forEach(item=>{
            var  list=item.taskList||[];
            for(var key in list){
                if(list[key].taskCode==taskid){
                    obj=list[key];
                    obj.planStartdate=startTime;
                    obj.planEnddate=endTime;
                    obj.startTime=startTime;
                    obj.endTime=endTime;
                    obj.isMiddleEnd=endMidFlg ;
                    obj.isMiddleStart=startMidFlg ;
                    obj.status=status;
                    isfind='true';
                    break;
                }
            }
        })
        if(isfind=='false'){
            var isDrag=$("#isDrag").val();
            var taskColor=$("#taskColor").val();
            ganttData.forEach(item=>{
                if(item.id ==rsCode){
                  var  obj={
                      planStartdate:startTime,
                      planEnddate:endTime,
                      startTime:startTime,
                      endTime:endTime,
                      isMiddleEnd:endMidFlg,
                      isMiddleStart:startMidFlg ,
                      status:status,
                      taskCode:taskid,
                      isDrag:isDrag=='true',
                      taskColor:taskColor,
                      rateColor:taskColor,
                      managerids:managerids,
                      rsDirector:rsDirector,
                  }
                   item.taskList.push(obj);
                }
            });
        }
        reloadGantt();
        for(var key in transferData){
            if(transferData[key].taskCode==taskid){
                transferData.splice(key,1);
                initTransTable();
                break;
            }
        }

    }


    function initTransTable() {
        febs.table.init({
            elem: $view.find('#transforTable'),
            data: transferData,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            skin: '',
            cols: [[
                {title: '项目编号', field: 'projectCode', minWidth: 20, hide: true},
                {title: '项目名称', field: 'projectName', edit: false, sort: false},
                {title: '任务编号', field: 'taskCode', minWidth: 120, edit: false},
                {title: '所需资源', field: 'rsName', minWidth: 120, edit: false},
                {title: '试验工时(天)', field: 'testDay', minWidth: 120, edit: false},
                {title: '项目经理', field: 'managers', minWidth: 120, edit: false},
                {title: '操作', toolbar: '#operatorTool', width: 200, align: 'left'},
            ]],
            done: function (res, curr, count) {
            }
        });
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    function getQueryParams() {
        ganStartTime=$taskStartDate.val();
         ganEndTime=$taskEndDate.val();
        return {
            managers: $searchForm.find('input[name="managers"]').val() == null ? "" : $searchForm.find('input[name="managers"]').val().trim(),
            projectCode: $searchForm.find('input[name="projectCode"]').val() == null ? "" : $searchForm.find('input[name="projectCode"]').val().trim(),
            taskCode: $searchForm.find('input[name="taskCode"]').val() == null ? "" : $searchForm.find('input[name="taskCode"]').val().trim(),
            mySchedule: mySchedule,
            status: $status.val() == null ? "" : $status.val().trim(),
            planStartdate:new Date(ganStartTime),
            planEnddate: new Date(ganEndTime),
            invalidate_ie_cache: new Date()
        };
    }

    function   addTransferData(taskid){
        var obj;
        ganttData.forEach(item=>{
            var  list=item.taskList||[];
            for(var key in list){
                if(list[key].taskCode==taskid){
                    obj=list[key];
                    list.splice(key,1);
                    break;
                }
            }
        });
     //   ganttData=  ganttData.filter(item=>item.taskList!=null);
        reloadGantt();
        transferData.push(obj);
        $("#pqdialog").hide();
        layer.msg("移至任务中转站成功!")

    }

    function  deleteSchedule(taskid){
        var obj;
        ganttData.forEach(item => {
            var list = item.taskList || [];
            for (var key in list) {
                if (list[key].taskCode == taskid) {
                    obj = list[key];
                    obj.planStartdate = null;
                    obj.planEnddate = null;
                    obj.startTime = null;
                    obj.endTime = null;
                    list.splice(key, 1);
                    break;
                }
            }

        });
      //  ganttData=  ganttData.filter(item=>item.taskList!=null);
        reloadGantt();
      //  transferData.push(obj);
    }

    function clearSchedule(taskid) {
        febs.modal.confirm('删除排期', '确定删除所选排期数据？', function () {
            febs.get(ctx + 'schedule/delete/' + taskid, null, function () {
                layer.msg('删除排期任务成功');
            });
        });
    }

    function detailTask(taskid) {
        febs.modal.open('查看排期', 'schedule/detail/' + taskid  , {
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '90%'],
            btn: ['关闭'],
            offset: ['5px', '5px'],
            yes: function (index, layero) {
                layer.close(index);
            },
            btn2: function (index, layero) {
            }, cancel: function () {

            }, data: {},
        });
    }


    table.on('tool(transforTable)', function (obj) {
        var data = obj.data,
            layEvent = obj.event;
        if (layEvent === 'edit') {
            modifyTask(data.taskCode,data.rsDirector);
        }

        if (layEvent === 'del') {
            clearSchedule(data.taskCode);
            //从任务中转站中移除记录
            for (var key in transferData) {
                if (transferData[key].taskCode == data.taskCode) {
                    transferData.splice(key, 1);
                    initTransTable();
                }
            }
        }
        if (layEvent === 'detail') {
            detailTask(data.taskCode);
        }
    });

    // 点击右键菜单其他的地方隐藏菜单
    $(document).on('mousedown', function () {
        $("#reamrkid").css("display","none");
        $("#reamrkid").html('');
        $("#pqdialog").hide();
    });

    $("#pqdialog").on("mousedown", function () {
        return false;
    }).on("contextmenu", function () {
        return false;
    });

    window.edit = function(e){
        febs.modal.open('修改排期', 'schedule/updateSchedule/' + taskId, {
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '90%'],
            btn: ['保存并提交'],
            offset: ['5px', '5px'],
            yes: function (index, layero) {
                $('#task-edit').find('#submit').trigger('click');
                var isSuccess = $(layero).find('#isSuccess').val();
                if(isSuccess=='false'){
                    return  false;
                }
                var startdate = $(layero).find('#planStartdate').val();
                var enddate = $(layero).find('#planEnddate').val();
                var starttime= $(layero).find('#planStarttime').val();
                var  endtime= $(layero).find('#planEndtime').val();
                var  startMidFlg=false;
                var rsCode=$(layero).find('#rsCode').val();
                var managerids=$(layero).find("#managerids").val();
                if("12:00"==starttime){
                    startMidFlg=true;
                }
                var endMidFlg=false;
                if("12:00"==endtime){
                    endMidFlg=true;
                }

                if(rsDirector==useridData){
                    modiSchdeuleStep(taskId,rsCode,managerids,rsDirector,startdate,enddate,startMidFlg,endMidFlg,"4");
                }else {
                    modiSchdeuleStep(taskId,rsCode,managerids,rsDirector,startdate,enddate,startMidFlg,endMidFlg,"2");
                }
                reloadGantt();
                layer.close(index);
            },
            btn2: function (index, layero) {
            },  data: {},
            success:function (index, layero){
            }
        });
    }

    window.detail = function(e){
        febs.modal.open('查看排期', '/schedule/detail/' + taskId, {
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '90%'],
            btn: ['关闭'],
            offset: ['5px', '5px'],
            yes: function (index, layero) {
                layer.close(index);
            },
            btn2: function (index, layero) {

            }, cancel: function () {

            }, data: {},
        });
    }

    window.del = function(e){
        febs.modal.confirm('删除排期', '确定删除所选排期数据？', function () {
            febs.get(ctx + 'schedule/delete/' + taskId, null, function () {
         //       febs.alert.success('删除排期任务成功');
                layer.msg("删除排期任务成功");
                //将排期数据移至中间站
                deleteSchedule(taskId);
                reloadGantt();
            });

        });
    }

    window.transfer = function(e){
        addTransferData(taskId);
    }

    window.approve = function(e){
        febs.modal.open('审核排期',ctx+ 'schedule/audit/' + taskId , {
            area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '90%'],
            btn: ['提交'],
            offset: ['5px', '5px'],
            yes: function (index, layero) {
                $('#task-edit').find('#submit').trigger('click');
                var isSuccess = $(layero).find('#isSuccess').val();
                if(isSuccess=='false'){
                    return  false;
                }
                var startdate = $(layero).find('#planStartdate').val();
                var enddate = $(layero).find('#planEnddate').val();
                var starttime= $(layero).find('#planStarttime').val();
                var  endtime= $(layero).find('#planEndtime').val();
                var  status=$(layero).find('#auditStatus').val();

                var startMidFlg=false;
                if("12:00"==starttime){
                    startMidFlg=true;
                }
                var endMidFlg=false;
                if("12:00"==endtime){
                    endMidFlg=true;
                }
                if(status==3){
                    deleteSchedule(taskId);
                }else {
                    modiSchdeuleStep(taskId,'','','',startdate,enddate,startMidFlg,endMidFlg,status);
                }

                reloadGantt();
                layer.close(index);
            }, success: function (index, layero) {
            }, data: {},
        });
    }



    // ===========  时间处理
    // 获取当前日期
    function getCurrentDay() {
        var now = new Date()
        var year = now.getFullYear();//获取当前年份
        var month = now.getMonth() + 1;//当前月份
        if (month < 10)
            month = "0" + month;
        else {
            month = month;
        }
        var day = now.getDate();//当前天份
        if (day < 10)
            day = "0" + day;
        else {
            day = day;
        }
        return year + "-" + month + "-" + day;
    }

    //当前日期往前推n天就传负数如-3，往后推就传正数如3
    function formatDateDorward(cuDate, n) {
        let date = new Date(cuDate)
        date.setDate(date.getDate() + n)
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        let day = date.getDate()
        m = m < 10 ? '0' + m : m
        day = day < 10 ? '0' + day : day
        return y + '-' + m + '-' + day
    }

    function formatNextYear(cuDate) {
        let date = new Date(cuDate)
        let y = date.getFullYear()+1
        let m = date.getMonth() + 1
        let day = date.getDate()
        m = m < 10 ? '0' + m : m
        day = day < 10 ? '0' + day : day
        return y + '-' + m + '-' + day
    }


    function checkData(url, condition) {
        var result='';
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data.data ;
            },
        });
        return result;
    }

    // 图例
    var positionFlg = 0;
    $('#legend').on('click', function () {
        $('#symbolPage').toggle(function () {
            if (positionFlg == 0) {
                positionFlg = 1
            } else {
                positionFlg = 0
                $("#symbolPage").css('top', '240px')
                $("#symbolPage").css('right', 'calc(1% + 50px)')
                $("#symbolPage").css('left', '')
                $("#symbolPage").hide()
            }
        });//toggle中添加任意函数，显示隐藏的时候会有动画特效
    })

    function initNotice() {
        if (reasonData) {
            layer.alert(reasonData, {
                icon: 0,
                shadeClose: true,
                title: '通知'
            });
        }
    }

});
